package com.cyanite.playlv2;

import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2api.PlayLv2Api;
import com.cyanite.playlv2api.types.Response;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AddFriendsActivity extends Activity{

    private final static int ITEM_SINA = 1;
    private final static int ITEM_TENCENT = 2;
    private final static int ITEM_163 = 3;
    private final static int ITEM_HOTMAIL = 4;
    private final static int ITEM_GOOGLE = 5;
    private final static int ITEM_ANOTHER = 6;

    private StateHolder mStateHolder;
    private ProgressDialog mProgressDialog;

    private View mFindFriendsByName;
    private View mEmailSina;
    private View mEmailTencent;
    private View mEmail163;
    private View mEmailHotmail;
    private View mEmailGmail;
    private View mEmailAnother;

    private RelativeLayout mLlSina;
    private RelativeLayout mLlTencent;
    private RelativeLayout mLl163;
    private RelativeLayout mLlHotmail;
    private RelativeLayout mLlGmail;
    private RelativeLayout mLlAnother;

    private Button mBtnSina;
    private Button mBtnTencent;
    private Button mBtn163;
    private Button mBtnHotmail;
    private Button mBtnGmail;
    private Button mBtnAnother;

    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));
        setContentView(R.layout.add_friends_activity);

        mStateHolder = new StateHolder();

        ensureUi();
    }


    private void ensureUi() {

        setTitle(getString(R.string.add_friends_activity_label));

        mLlSina = (RelativeLayout)findViewById(R.id.llSina);
        mLlTencent = (RelativeLayout)findViewById(R.id.llTencent);
        mLl163 = (RelativeLayout)findViewById(R.id.ll163);
        mLlHotmail = (RelativeLayout)findViewById(R.id.llHotmail);
        mLlGmail = (RelativeLayout)findViewById(R.id.llGoogle);
        mLlAnother = (RelativeLayout)findViewById(R.id.llAnother);

        initEmailLayoutClickEvent();
        initButtonClickEvent();
        closeAllItem();
    }

    private void initButtonClickEvent(){

        mBtnSina = (Button)findViewById(R.id.btnAddSina);
        mBtnSina.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemSendEffect(ITEM_SINA);
            }
        });

        mBtnTencent = (Button)findViewById(R.id.btnAddTencent);
        mBtnTencent.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemSendEffect(ITEM_TENCENT);
            }
        });

        mBtn163 = (Button)findViewById(R.id.btnAdd163);
        mBtn163 .setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemSendEffect(ITEM_163);
            }
        });

        mBtnHotmail = (Button)findViewById(R.id.btnAddHotmail);
        mBtnHotmail.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemSendEffect(ITEM_HOTMAIL);
            }
        });

        mBtnGmail = (Button)findViewById(R.id.btnAddGoogle);
        mBtnGmail.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemSendEffect(ITEM_GOOGLE);
            }
        });

        mBtnAnother = (Button)findViewById(R.id.btnAddAnother);
        mBtnAnother.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemSendEffect(ITEM_ANOTHER);
            }
        });
    }

    private void initEmailLayoutClickEvent() {

        mFindFriendsByName = findViewById(R.id.addFromPlayLv2);
        mFindFriendsByName.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(AddFriendsActivity.this,
                        AddFriendsByUserInputActivity.class);
                intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
                        AddFriendsByUserInputActivity.INPUT_TYPE_NAME_OR_PHONE);
                startActivity(intent);
                finish();
            }
        });

        mEmailSina = findViewById(R.id.addSinaFriends);
        mEmailSina.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemClickEffect(ITEM_SINA);
            }
        });

        mEmailTencent = findViewById(R.id.addTencentFriends);
        mEmailTencent.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemClickEffect(ITEM_TENCENT);
            }
        });

        mEmail163 = findViewById(R.id.add163Friends);
        mEmail163.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemClickEffect(ITEM_163);
            }
        });

        mEmailHotmail = findViewById(R.id.addHotmailFriends);
        mEmailHotmail.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemClickEffect(ITEM_HOTMAIL);
            }
        });

        mEmailGmail = findViewById(R.id.addGoogleFriends);
        mEmailGmail.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemClickEffect(ITEM_GOOGLE);
            }
        });

        mEmailAnother = findViewById(R.id.addAnotherFriends);
        mEmailAnother.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                handleItemClickEffect(ITEM_ANOTHER);
            }
        });
    }

    private void handleItemClickEffect(int item)    {
        closeAllItem();
        switch( item ){
            case ITEM_SINA:
                mLlSina.setVisibility(View.VISIBLE);
                break;
            case ITEM_TENCENT:
                mLlTencent.setVisibility(View.VISIBLE);
                break;
            case ITEM_163:
                mLl163.setVisibility(View.VISIBLE);
                break;
            case ITEM_HOTMAIL:
                mLlHotmail.setVisibility(View.VISIBLE);
                break;
            case ITEM_GOOGLE:
                mLlGmail.setVisibility(View.VISIBLE);
                break;
            case ITEM_ANOTHER:
                mLlAnother.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void handleItemSendEffect(int item)    {
        TextView tvMail = null;
        switch( item ){
            case ITEM_SINA:
                tvMail  = (TextView)findViewById(R.id.tvSina);
                mStateHolder.startTaskAddFriends(this, tvMail.getText().toString());
                break;
            case ITEM_TENCENT:
                tvMail  = (TextView)findViewById(R.id.tvTencent);
                mStateHolder.startTaskAddFriends(this, tvMail.getText().toString());
                break;
            case ITEM_163:
                tvMail  = (TextView)findViewById(R.id.tv163);
                mStateHolder.startTaskAddFriends(this, tvMail.getText().toString());
                break;
            case ITEM_HOTMAIL:
                tvMail  = (TextView)findViewById(R.id.tvHotmail);
                mStateHolder.startTaskAddFriends(this, tvMail.getText().toString());
                break;
            case ITEM_GOOGLE:
                tvMail  = (TextView)findViewById(R.id.tvGoogle);
                mStateHolder.startTaskAddFriends(this, tvMail.getText().toString());
                break;
            case ITEM_ANOTHER:
                tvMail  = (TextView)findViewById(R.id.tvAnother);
                mStateHolder.startTaskAddFriends(this, tvMail.getText().toString());
                break;
            default:
                break;
        }
    }

    private void closeAllItem() {
        mLlSina.setVisibility(View.GONE);
        mLlTencent.setVisibility(View.GONE);
        mLl163.setVisibility(View.GONE);
        mLlHotmail.setVisibility(View.GONE);
        mLlGmail.setVisibility(View.GONE);
        mLlAnother.setVisibility(View.GONE);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isFinishing()) {
            mStateHolder.cancelTasks();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLoggedOutReceiver);
    }

    private ProgressDialog showProgressDialog() {
        if (mProgressDialog == null) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.add_friends_progress_bar_message_send_request));
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            mProgressDialog = dialog;
        }
        mProgressDialog.show();
        return mProgressDialog;
    }

    private void dismissProgressDialog() {
        try {
            mProgressDialog.dismiss();
        } catch (IllegalArgumentException e) {
            // We don't mind. android cleared it for us.
        }
    }

    private void onAddFriendsTaskComplete(Response response, Exception ex) {
        mStateHolder.setIsRunningAddFriendsTask(false);
        dismissProgressDialog();

        if (response != null && response.getValue().equals("0")) {
            Toast.makeText(AddFriendsActivity.this,
                    getResources().getString(R.string.add_friends_request_sent_ok),
                    Toast.LENGTH_LONG).show();
        } else {
            NotificationsUtil.ToastReasonForFailure(this, ex);
            finish();
        }
    }

    private static class AddFriendsTask extends AsyncTask<Void, Void, Response> {

        private AddFriendsActivity mActivity;
        private Exception mReason;
        private String mEmail;

        public AddFriendsTask(AddFriendsActivity activity, String email) {
            mActivity = activity;
            mEmail = email;
        }

        @Override
        protected void onPreExecute() {
            mActivity.showProgressDialog();
        }

        @Override
        protected Response doInBackground(Void... params) {
            PlayLv2Api playlv2api = ((PlayLv2) mActivity.getApplication()).getPlayLv2Api();
            try {
                Response response = playlv2api.friendRequestsByEmail(mEmail);
                if (response == null)   response = new Response();
                return response;
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.onAddFriendsTaskComplete(response, mReason);
            }
        }

        @Override
        protected void onCancelled() {
            mActivity.dismissProgressDialog();
        }

        public void setActivity(AddFriendsActivity activity) {
            mActivity = activity;
        }
    }

    private static class StateHolder {

        private AddFriendsTask mTaskAddFriends;
        private boolean mIsRunningAddFriendsTask;

        public StateHolder() {
            mIsRunningAddFriendsTask = false;
        }

        public void startTaskAddFriends(AddFriendsActivity activity, String email) {
            if (!mIsRunningAddFriendsTask) {
                mIsRunningAddFriendsTask = true;
                mTaskAddFriends = new AddFriendsTask(activity, email);
                mTaskAddFriends.execute();
            }
        }

        public void setIsRunningAddFriendsTask(boolean isRunning) {
            mIsRunningAddFriendsTask = isRunning;
        }

        public void cancelTasks() {
            if (mTaskAddFriends != null) {
                mTaskAddFriends.setActivity(null);
                mTaskAddFriends.cancel(true);
            }
        }
    }
}
